/**
 * 
 */
package org.xabber.storage;

import java.io.File;
import java.util.ArrayList;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 数据库管理类,负责数据库的创建,所有注册表的创建和删除,表结构的转换升级.
 * @author hljdrl@gmail.com
 * 
 */
public class DataBaseManager extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "database.db";
	private static final int DATABASE_VERSION = 1;

	private static final SQLiteException DOWNGRAD_EXCEPTION = new SQLiteException(
			"Database file was deleted");

	private final ArrayList<DatabaseTable> registeredTables;

	private final static DataBaseManager instance;
	static {
		instance = new DataBaseManager();
	}
	public static DataBaseManager getInstance() {
		return instance;
	}

	public DataBaseManager() {
		super(DBApplication.getInstance(), DATABASE_NAME, null, DATABASE_VERSION);
		registeredTables = new ArrayList<DatabaseTable>();
	}

	public void addTable(DatabaseTable table) {
		registeredTables.add(table);
	}

	public void removeAccount(String account) {
		for (DatabaseTable table : registeredTables)
			if (table instanceof AbstractAccountTable)
				((AbstractAccountTable) table).removeAccount(account);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		for(DatabaseTable table : registeredTables){
			table.create(db);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if(oldVersion>newVersion){
			File file = new File(db.getPath());
			file.delete();
			throw DOWNGRAD_EXCEPTION;
		}else {
			while(oldVersion<newVersion){
				oldVersion+=1;
				migrate(db, oldVersion);
				for(DatabaseTable table : registeredTables){
					table.migrate(db, oldVersion);
				}
			}
		}
	}
	/**
	 * Called on database migration.
	 * 
	 * @param db
	 * @param toVersion
	 */
	private void migrate(SQLiteDatabase db, int toVersion) {
		switch (toVersion) {
		case 1:
			for(DatabaseTable table : registeredTables){
				table.migrate(db, toVersion);
			}
			break;
		default:
			break;
		}
	}

	public static void execSQL(SQLiteDatabase db, String sql) {
		db.execSQL(sql);
	}

	public static void dropTable(SQLiteDatabase db, String table) {
		execSQL(db, "DROP TABLE IF EXISTS " + table + ";");
	}

	public static void renameTable(SQLiteDatabase db, String table,
			String newTable) {
		execSQL(db, "ALTER TABLE " + table + " RENAME TO " + newTable + ";");
	}

	public void onClear() {
		for (DatabaseTable table : registeredTables)
			table.clear();
	}
	public void onLoad() {
		try {
			getWritableDatabase(); // Force onCreate or onUpgrade
		} catch (SQLiteException e) {
			if (e == DOWNGRAD_EXCEPTION) {
				// Downgrade occured
			} else {
				throw e;
			}
		}
	}

}
